//用户
(function(){
	var db_table_name = "user";
	var db = require("../db/index");
	var md5 = require("../_include/md5");

	//构造函数
	var _con = function (info,isAnonymous){
		var self = this;
		//身份编号
		self._id = "U_"+Math.random().toString(16).substr(2)+(+new Date).toString(16);
		//操作记录
		self._his = [];
		//订单列表
		self.achs = [];
		//收获地址
		self.uas = [];
		//默认收货地址
		self.default_ua_id;
		//额外信息
		self.info = info;
		//名字不区分大小写
		self.info.name = info.name.toLowerCase();
		//密码非明文存储
		self.info.password = md5.md5_2(info.password);
		//推荐积分
		self.rec_int = 0;
		//购买积分
		self.buy_int = 0;
		//收藏夹
		self.collect = [];
		if (isAnonymous) {
			//保存用户信息
			db.insert(db_table_name,self);
			//日志打印
			console.log("临时生成了一个匿名用户：",info.name);
		}else{
			//保存用户信息
			db.insert(db_table_name,self);
			//日志打印
			console.log("注册了一个用户：",info.name);
		}
	};
	//PS:模块的暴露放在require skill前面，因为二者互相依赖
	module.exports = _con;
	//技能
	_con.prototype = require("./skill");

	//静态方法
	_con.get = function(Id){
		var result = db.find_by_id(db_table_name,Id);
		if(result){
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	_con.getAnonymous = function(){
		return new _con({
			name:"Anonymous",
			isAnonymous:true,
			email:"Anonymous@Anonymous.com",
			password:"mywebsite.com"
		},true);
	};
	_con.login = function(user_info){
		user_info.name = user_info.name.toLowerCase();
		var mybey_user = db.find_one(db_table_name,{
			info:{
				name:user_info.name
			}
		});
		if (!mybey_user) {
			console.log("找不到用户名为：“",user_info.name,"”的用户！");
			throw "找不到用户名为：“",user_info.name,"”的用户！";
		}else if(mybey_user.info.password!==md5.md5_2(user_info.password)){
			console.log("密码错误！");
			throw "密码错误";
		}else{
			console.log(user_info.name,"登陆成功");
			return mybey_user;
		}
	};
}());
